<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Check, Close } from '@element-plus/icons-vue'
import cloneDeep from 'lodash-es/cloneDeep'

defineOptions({
  name: 'UserDrawer',
})

// 表单验证规则
const formRules = {
  phone: [{ required: true, message: '请输入登录账号!', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码!', trigger: 'blur' }],
  name: [{ required: true, message: '请输入中文姓名!', trigger: 'blur' }],
  openStatus: [{ required: true, message: '请选择状态!', trigger: 'change' }],
  role: [{ required: true, message: '请选择角色!', trigger: 'change' }],
}

interface UserFormData {
  id?: number
  phone?: string
  password?: string
  name?: string
  english_name?: string
  last_login?: string
  gender?: '0' | '1' | '2'
  openStatus?: 'OPEN' | 'CLOSE'
  role?: string
  created_at?: string
}

interface DrawerProps {
  title: string
  isView: boolean
  row: Partial<UserFormData>
  api?: (params: any) => Promise<any>
  getTableList?: () => void
}

const formData = ref<Partial<UserFormData>>({})
const drawerVisible = ref(false)
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: '',
  row: {},
})

// 接收父组件传过来的参数
function acceptParams(params: DrawerProps) {
  formData.value = cloneDeep(params.row)
  drawerProps.value = params
  drawerVisible.value = true
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>()
async function handleSubmit() {
  const valid = await ruleFormRef.value?.validate()
  if (!valid) {
    return
  }

  try {
    let params = cloneDeep(formData.value)
    await drawerProps.value.api!(params)
    ElMessage.success({ message: `${drawerProps.value.title}账号成功！` })
    drawerProps.value.getTableList!()
    drawerVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败，请重试')
  }
}

defineExpose({
  acceptParams,
})
</script>

<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="650px"
    :title="`${drawerProps.title}账号`"
  >
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="formRules"
      :disabled="drawerProps.isView"
      :model="formData"
      :hide-required-asterisk="drawerProps.isView"
    >
      <!-- 登录账号 -->
      <el-form-item prop="phone" label="登录账号">
        <el-input v-model="formData.phone" placeholder="请输入登录账号" clearable />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password" label="密码">
        <el-input
          v-model="formData.password"
          placeholder="请输入密码"
          show-password
          clearable
        />
      </el-form-item>

      <!-- 中文姓名 -->
      <el-form-item prop="name" label="中文姓名">
        <el-input v-model="formData.name" placeholder="请输入中文姓名" clearable />
      </el-form-item>

      <!-- 英文姓名 -->
      <el-form-item label="英文姓名" prop="english_name">
        <el-input
          v-model="formData.english_name"
          placeholder="请输入英文姓名（可选）"
          clearable
        />
      </el-form-item>

      <!-- 最近登录时间 -->
      <el-form-item label="最近登录">
        <el-input v-model="formData.last_login" disabled placeholder="自动填充或为空" />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="gender">
        <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%">
          <el-option label="未知" value="0" />
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态" prop="openStatus">
        <el-switch
          v-model="formData.openStatus"
          active-value="OPEN"
          inactive-value="CLOSE"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
        />
      </el-form-item>

      <!-- 角色 -->
      <el-form-item label="角色" prop="role">
        <el-select v-model="formData.role" placeholder="请选择角色" style="width: 100%">
          <el-option label="普通用户" value="1" />
          <el-option label="管理员" value="2" />
        </el-select>
      </el-form-item>

      <!-- 创建时间 -->
      <el-form-item label="创建时间">
        <el-input v-model="formData.created_at" disabled placeholder="自动生成" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>
